﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.GISClient;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using System.Threading;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using System.Configuration;
using ESRI.ArcGIS.Server;

namespace ClientApplication
{
    public partial class MainClient : Form
    {
        //gisserver info
        GisServer gisServer = new GisServer();
        //DBServer Info
        DBServer dbServer = new DBServer();
        //鹰眼加载开始的标志
        private bool mapStat = false;
        //预测服务管理窗体对象
        private ServiceMng myServiceMng = null;
        //GISServer连接工具类的对象
        private GISServerMng pSerMng = null;
        //GISServerUrl
        private string serverUrl;

        public string ServerUrl
        {
            get { return serverUrl; }
            set { serverUrl = value; }
        }
        //GISServer连接的用户名密码
        private string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
        private string passowrd;

        public string Passowrd
        {
            get { return passowrd; }
            set { passowrd = value; }
        }
        //全局变量，存储Server服务器上的所有的Service
        private List<IAGSServerObjectName> pList;
        //当前加载图层的ServerObjName对象
        private IAGSServerObjectName serObjName = null;
        //当前加载的MapLayer
        private IMapServerLayer pMapServerLayer = new MapServerLayerClass();
        //Admin连接对象
        private IAGSServerConnection customerConn = null;

        public IAGSServerConnection CustomerConn
        {
            get { return customerConn; }
            set { customerConn = value; }
        }


        //custom的连接对象
        private IServerObjectAdmin serverAdmin = null;

        public IServerObjectAdmin ServerAdmin
        {
            get { return serverAdmin; }
            set { serverAdmin = value; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public MainClient(string url, string username, string password)
        {
            this.ServerUrl = url;
            this.UserName = username;
            this.Passowrd = password;
            InitializeComponent();
            //pSerMng = new GISServerMng(ServerUrl, UserName, Passowrd);
        }
        public MainClient(GisServer gis, DBServer db)
        {
            this.gisServer = gis;
            this.dbServer = db;
            InitializeComponent();
            //pSerMng = new GISServerMng(ServerUrl, UserName, Passowrd);
        }




        private void MainClient_Load(object sender, EventArgs e)
        {
            //axTOCControl1.OcxState = axToolbarControl1.OcxState;
            axTOCControl1.SetBuddyControl(axMapControl1);
        }

        /// <summary>
        /// 在连接过程中同时获取custom和admin的连个连接并且返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            ServerConn pServerConn = new ServerConn(gisServer);
            pServerConn.ShowDialog();
            if (pServerConn.DialogResult == DialogResult.OK)
            {
                //this.pList = pServerConn.PList;
                //获得custom的连接对象
                CustomerConn = pServerConn.CustomerConn;
                //获得admin的连接对象
                ServerAdmin = pServerConn.ServerAdmin;
            }
            pServerConn.Close();
        }
        /// <summary>
        /// 服务加载按钮点击事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if ((this.CustomerConn != null) && (this.ServerAdmin != null))
            {
                MapServiceManager pMapSerMng = new MapServiceManager(this.CustomerConn, false);
                pMapSerMng.ShowDialog();
                if (pMapSerMng.DialogResult == DialogResult.OK)
                {
                    serObjName = null;

                    //启用多线程加载

                    serObjName = pMapSerMng.SelectedServerObj;

                    this.backgroundWorker_loadMap.RunWorkerAsync();

                    //可以启动鹰眼加载
                    //this.mapStat = true;

                }
            }
            else
            {
                MessageBox.Show("请先连接GIS服务器", "错误操作", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// GIS服务管理按钮点击事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolBtn_gismng_Click(object sender, EventArgs e)
        {
            //进入GISServer管理
            //MapServiceManager myMapMng = new MapServiceManager(this.pSerMng, this.pList);
            //myMapMng.Show();
            if ((this.CustomerConn != null) && (this.ServerAdmin != null))
            {
                //进入编辑模式
                MapServiceManager pMapSerMng = new MapServiceManager(this.ServerAdmin, true);
                pMapSerMng.Show();
            }
            else
            {
                MessageBox.Show("请先连接GIS服务器", "错误操作", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 预测服务管理按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolBtn_service_Click(object sender, EventArgs e)
        {
            //因为是非模式窗口启动，在调用之前需要判断是否已经创建过预测服务管理窗体
            //必须在this中保存预测服务管理对象
            if (myServiceMng != null)
            {
                if (myServiceMng.IsDisposed)
                {
                    myServiceMng = new ServiceMng();
                    myServiceMng.Show();
                }
                else
                {
                    if (myServiceMng.Visible != true)
                    {
                        //如果已经创建了预测服务管理窗体对象,管理窗体不可见
                        //点击按钮只重新显示
                        myServiceMng.Show();
                    }
                    else
                    {
                        //使管理窗体可见
                        myServiceMng.Visible = true;
                        myServiceMng.WindowState = FormWindowState.Normal;
                    }
                }

            }
            else
            {
                myServiceMng = new ServiceMng();
                myServiceMng.Show();
            }
        }

        private void toolBtn_data_Click(object sender, EventArgs e)
        {
            DataMng myDataMng = new DataMng(this.dbServer);
            myDataMng.Show();
        }
        #region 鹰眼功能



        private void axMapControl1_OnExtentUpdated(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            //MessageBox.Show("OnExtentUpdated");
            ////得到新的范围
            //IEnvelope pEnvelop = (IEnvelope)e.newEnvelope;

            //IGraphicsContainer pGraphicsContainer = axMapControl2.Map as IGraphicsContainer;

            //IActiveView pActiveView = pGraphicsContainer as IActiveView;

            ////在绘制前，清除axMapControl2中的任何图形元素

            //pGraphicsContainer.DeleteAllElements();

            //IRectangleElement pRectangleEle = new RectangleElementClass();

            //IElement pElement = pRectangleEle as IElement;

            //pElement.Geometry = pEnvelop;

            ////设置鹰眼图中的红线框 

            //IRgbColor pColor = new RgbColorClass();

            //pColor.Red = 255;

            //pColor.Green = 0;

            //pColor.Blue = 0;

            //pColor.Transparency = 255;

            ////产生一个线符号对象

            //ILineSymbol pOutline = new SimpleLineSymbolClass();

            //pOutline.Width = 3;

            //pOutline.Color = pColor;

            ////设置颜色属性

            //pColor = new RgbColorClass();

            //pColor.Red = 255;

            //pColor.Green = 0;

            //pColor.Blue = 0;

            //pColor.Transparency = 0;

            ////设置填充符号的属性

            //IFillSymbol pFillSymbol = new SimpleFillSymbolClass();

            //pFillSymbol.Color = pColor;

            //pFillSymbol.Outline = pOutline;

            //IFillShapeElement pFillShapeEle = pElement as IFillShapeElement;

            //pFillShapeEle.Symbol = pFillSymbol;

            //pGraphicsContainer.AddElement((IElement)pFillShapeEle, 0);

            //pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

            // 得到新范围
            IEnvelope pEnv = (IEnvelope)e.newEnvelope;
            IGraphicsContainer pGra = axMapControl2.Map as IGraphicsContainer;
            IActiveView pAv = pGra as IActiveView;
            // 在绘制前，清除 axMapControl2 中的任何图形元素
            pGra.DeleteAllElements();
            IRectangleElement pRectangleEle = new RectangleElementClass();
            IElement pEle = pRectangleEle as IElement;
            pEle.Geometry = pEnv;
            // 设置鹰眼图中的红线框
            IRgbColor pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 255;
            // 产生一个线符号对象
            ILineSymbol pOutline = new SimpleLineSymbolClass();
            pOutline.Width = 2;
            pOutline.Color = pColor;
            // 设置颜色属性
            pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 0;
            // 设置填充符号的属性
            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
            pFillSymbol.Color = pColor;
            pFillSymbol.Outline = pOutline;
            IFillShapeElement pFillShapeEle = pEle as IFillShapeElement;
            pFillShapeEle.Symbol = pFillSymbol;
            pGra.AddElement((IElement)pFillShapeEle, 0);
            // 刷新
            pAv.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        private void axMapControl1_OnMapReplaced(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMapReplacedEvent e)
        {
            //MessageBox.Show("OnMapReplaced");

            //if (axMapControl1.LayerCount > 0)
            //{
            //    axMapControl2.Map = new MapClass();

            //    for (int i = 0; i <= axMapControl1.Map.LayerCount - 1; i++)
            //    {
            //        axMapControl2.AddLayer(axMapControl1.get_Layer(i));
            //    }
            //    axMapControl2.Extent = axMapControl1.Extent;

            //    axMapControl2.Refresh();
            //}
            // 前面代码省略
            // 当主地图显示控件的地图更换时，鹰眼中的地图也跟随更换
            this.axMapControl2.Map = new MapClass();
            // 添加主地图控件中的所有图层到鹰眼控件中
            for (int i = 1; i <= this.axMapControl1.LayerCount; i++)
            {
                this.axMapControl2.AddLayer(this.axMapControl1.get_Layer(this.axMapControl1.LayerCount - i));
            }
            // 设置 MapControl 显示范围至数据的全局范围
            this.axMapControl2.Extent = this.axMapControl1.FullExtent;
            // 刷新鹰眼控件地图
            this.axMapControl2.Refresh();
        }


        private void axMapControl2_OnMouseMove(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseMoveEvent e)
        {
            //if (e.button == 1)
            //{
            //    IPoint pPoint = new PointClass();

            //    pPoint.PutCoords(e.mapX, e.mapY);

            //    axMapControl1.CenterAt(pPoint);

            //    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            //}
            // 如果不是左键按下就直接返回
            if (e.button != 1) return;
            IPoint pPoint = new PointClass();
            pPoint.PutCoords(e.mapX, e.mapY);
            this.axMapControl1.CenterAt(pPoint);
            this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }

        private void axMapControl2_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {
            //if (axMapControl2.Map.LayerCount > 0)
            //{
            //    if (e.button == 1)
            //    {
            //        IPoint pPoint = new PointClass();

            //        pPoint.PutCoords(e.mapX, e.mapY);

            //        axMapControl1.CenterAt(pPoint);

            //        axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

            //    }
            //    else if (e.button == 2)
            //    {
            //        IEnvelope pEnv = axMapControl2.TrackRectangle();

            //        axMapControl1.Extent = pEnv;

            //        axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            //    }
            //}
            if (this.axMapControl2.Map.LayerCount != 0)
            {
                // 按下鼠标左键移动矩形框
                if (e.button == 1)
                {
                    IPoint pPoint = new PointClass();
                    pPoint.PutCoords(e.mapX, e.mapY);
                    IEnvelope pEnvelope = this.axMapControl1.Extent;
                    pEnvelope.CenterAt(pPoint);
                    this.axMapControl1.Extent = pEnvelope;
                    this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }
                // 按下鼠标右键绘制矩形框
                else if (e.button == 2)
                {
                    IEnvelope pEnvelop = this.axMapControl2.TrackRectangle();
                    this.axMapControl1.Extent = pEnvelop;
                    this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }
            }
        }
        #endregion
        private void 系统配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Config myConfig = new Config(this.ServerUrl, this.UserName, this.Passowrd);
            Config myConfig = new Config(gisServer, dbServer);
            myConfig.ShowDialog();
            if (myConfig.DialogResult == DialogResult.OK)
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                
                try
                {
                    //读取GISServer Info
                    gisServer.GisUrl = config.AppSettings.Settings["gisserver"].Value;

                    gisServer.GisUsername = config.AppSettings.Settings["gisusername"].Value;

                    gisServer.GisPassword = config.AppSettings.Settings["gispassword"].Value;

                    //read dbServer info
                    dbServer.DbUsername = config.AppSettings.Settings["dbusername"].Value;
                    dbServer.DbPassword = config.AppSettings.Settings["dbpassword"].Value;
                    dbServer.DbUrl = config.AppSettings.Settings["dbserver"].Value;
                    dbServer.DbName = config.AppSettings.Settings["dbname"].Value;

                }
                catch (NullReferenceException ne)
                {

                    throw ne;
                }
            }
        }
        #region 通过线程加载地图
        private void backgroundWorker_loadMap_DoWork(object sender, DoWorkEventArgs e)
        {

            MessageBox.Show("开始加载地图...\n" + "\n" + serObjName.Name + "\n" + serObjName.Type);

            //加载地图前清空TOC，MapContro1,2
            //this.pMapServerLayer = null;

            this.axMapControl1.ClearLayers();
            this.axMapControl2.ClearLayers();
            this.axMapControl1.Refresh();

            IName pName = (IName)serObjName;

            IAGSServerObject pServerObject = (IAGSServerObject)pName.Open();

            IMapServer pMapServer = (IMapServer)pServerObject;

            pMapServerLayer.ServerConnect(serObjName, pMapServer.DefaultMapName);


        }

        private void backgroundWorker_loadMap_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("地图加载完成");
            axMapControl1.AddLayer(pMapServerLayer as ILayer);

            axMapControl1.Refresh();
            // 当主地图显示控件的地图更换时，鹰眼中的地图也跟随更换
            this.axMapControl2.Map = new MapClass();
            // 添加主地图控件中的所有图层到鹰眼控件中
            for (int i = 1; i <= this.axMapControl1.LayerCount; i++)
            {
                this.axMapControl2.AddLayer(this.axMapControl1.get_Layer(this.axMapControl1.LayerCount - i));
            }
            // 设置 MapControl 显示范围至数据的全局范围
            this.axMapControl2.Extent = this.axMapControl1.FullExtent;
            // 刷新鹰眼控件地图
            this.axMapControl2.Refresh();
        }
        #endregion

        #region 窗体最小化到系统托盘

        private void ServiceMng_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = false;
        }
        #endregion
        /// <summary>
        /// 主窗体关闭按钮点击事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断预测服务窗体对象是否已被实例化
            if (MessageBox.Show("确认关闭预测服务管理界面吗？\n\n关闭请点击YES，不关闭并最小化到系统托盘请点击NO", "确认关闭GIS管理系统", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                //进行关闭操作，检查服务状态
                if (this.myServiceMng != null)
                {
                    if (MessageBox.Show("确认关闭预测服务吗？\n\n关闭请点击YES，不关闭请点击NO", "确认关闭预测服务", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        this.myServiceMng = null;
                        this.Dispose();
                        Application.Exit();
                    }
                    else
                    {
                        MessageBox.Show("建议最小化到系统托盘");
                        e.Cancel = true;
                    }
                }
                //Application.Exit();
            }
            else
            {
                e.Cancel = true;
                //
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                this.notifyIcon1.Visible = true;
            } 
        }






    }
}